var chinese = ["零","一", "二", "三", "四", "五", "六", "七", "八", "九"];
var temp = $.trim($("#item_temp").html());
var vipId = $("#vipId").val();
var shopId = $("#shopId").val();
var $contentDiv = $(".am-g-striped");
var itemMap;
var employeeMap;
var empSelectTemp = "<li class='am-padding-sm'>请选择{2}：</li><li class='am-padding-sm'><input name='detailList[0].scheList[{0}].roleId' type='hidden' value='{1}'></input>"+
"<input name='detailList[0].scheList[{0}].state' type='hidden' value='10A'></input>"+
"<select name='detailList[0].scheList[{0}].employeeId' class='item-emp-sele'></select></li>";

function convertToChinese(num){
	var str = num.toString();
	var len = num.toString().length;
	var C_Num = [];
	for(var i = 0; i < len; i++){
		C_Num.push(chinese[str.charAt(i)]);
	}
	if(len==1){
		return chinese[num];
	}
	if(len==2){
		var C_Num = [];
		var first=chinese[str.charAt(0)];
		if(first!='一')
			C_Num.push(first);
		C_Num.push('十');
		var second=chinese[str.charAt(1)];
		if(second!='零')
			C_Num.push(second);
		return C_Num.join('');
	}
	return num;
}
$("#increase").click(function() {
	var n = $("#mdse-num").html();
	var num = parseInt(n) + 1;
	if (num == 0) {
		return
	}
	$("#mdse-num").html(num);
});

$("#decrease").click(function() {
	var n = $("#mdse-num").html();
	var num = parseInt(n) - 1;
	if (num == 0) {
		return
	}
	$("#mdse-num").html(num);
});

function changeItemNum(){
	$(".item-desc-num").each(function(index) {
		$(this).html(convertToChinese(index+1));
		$(this).parents("div.am-text-blue").find(":input,select").attr("name",function(n,old){
			if(old!=null&&old!=""){
				return old.replace(/[\d+]/,index);
			}
		});
	});
}
//删除
$contentDiv.on("click", "a", function() {
	var result = confirm("确定删除？");
	if(!result){
		return;
	}
	$div = $(this).parents("div.am-text-blue");
	var packageId = $div.find("input[name$='packageId']").val();
	var orderDetailId = $div.find("input[name$='orderDetailId']").val();
	if(orderDetailId){//是否已保存
		var detailIds;
		if(packageId){//套餐
			$("div[data-id='"+packageId+"']").each(function(i) {
				if(i==0){
					detailIds=$(this).find("input[name$='orderDetailId']").val();
				}else{
					detailIds = detailIds+","+$(this).find("input[name$='orderDetailId']").val();
				}
			});
		}else{
			detailIds=orderDetailId;
		}
		var orderInfoId = $("#orderInfoId").val();
		if(orderInfoId){
			$.ajax({
				type : 'POST',
				url: ctx+"/weixin/employee/deleteOrderDetail",
				dataType: "json",
				data:"detailIds="+detailIds+"&orderInfoId="+orderInfoId,
				success: function (data) {
					if (data.success) {
						if(packageId){//套餐
							$("div[data-id='"+packageId+"']").remove();
						}else{
							$div.remove();
						}
						changeItemNum();
						initNextServiceEmp();

					}else{
						Comm.msg(data.msg);
						return;
					}
				},
				error: function () {
					Comm.msg("删除失败，请重试");
					return;
				}
			});
		}
	}else{
		if(packageId){//套餐
			$("div[data-id='"+packageId+"']").remove();
		}else{
			$div.remove();
		}
		changeItemNum();
		initNextServiceEmp();
	}
});

function initItemModal(){
	itemMap = null;
	var $cateSele = $("#item-cate-sele");
	$cateSele.empty();
	//初始化下拉框
	$.ajax({
		url : ctx+"/weixin/vip/service/" + shopId,
		type : "GET",
		success : function(data) {
			if(data.records==0){
				$("<option/>").html("该门店暂无服务项目").val("").appendTo(
				"#item-sele");
				return;
			}
			//jquery解析map数据
			itemMap = data.rowsMap;
			$.each(data.rowsMap, function(key, value) {
				var items = itemMap[key];
				if(items){
					$("<option/>").html(key).val(
							key).appendTo("#item-cate-sele");
				}
			});
			initItemSele($("#item-cate-sele").val());
		}
	});
}

$("#item-cate-sele").change(function () {
	initItemSele($(this).val());
});

function initItemSele(itemCategoryId){
	var items = this.itemMap[itemCategoryId];
	$("#item-sele").empty();
	$.each(items, function(i, item) {
		var price;
		if(vipId){
			price = item.vipPrice;
		}else{
			price = item.noVipPrice;
		}
		$("<option/>").html(item.serviceItemName).val(
				item.serviceItemId).data('price',price).data('noVipPrice',item.noVipPrice).appendTo("#item-sele");
	});
}

$("#mdse-sele").change(function () {
	chanageMdsePrice($(this).find('option').eq(this.selectedIndex).data("price"));
	$("#mdse-num").html("1");
});

$contentDiv.on("change", ".item-emp-sele", function() {
	initNextServiceEmp();
});

function chanageMdsePrice(price){
	$("#mdse-price").html(price);
}

function initNextServiceEmp(){
	var orderScheduleId = $("#orderScheduleId").val();
	var $nextEmp=$("#next-service-emp");
	$nextEmp.empty();
	$(".item-emp-sele").each(function(i) {
		var val = $(this).val();
		if(!val)
			return;
		var state = $(this).prev().val();
		if(state!='10A')
			return;
		if(orderScheduleId){
			var $scheId = $(this).parent().prev().prev().prev();
			var scheName = $scheId.attr("name")
			if(scheName&&scheName.indexOf("orderScheduleId")>0){
				var tmpId = $scheId.val();
				if(tmpId==orderScheduleId&&val==employeeId){
					return;
				}
			}
		}
		var name = $(this).find('option').eq(this.selectedIndex).text();
		name = name.substring(0, name.indexOf("("))+"-"+$(this).parents("div.am-text-blue").find("input[name$='mdseServiceName']").val();
		$("<option/>").html(name).val(val).appendTo($nextEmp);
	});
}

$("#add-item-btn").click(function() {
	var itemId = $("#item-sele").val();
	if(!itemId){
		Comm.msg("请先选择项目");
		return;
	}
	if($("div[data-id='"+itemId+"']").length>0){
		$("#item-modal").modal('close');
		Comm.msg("该项目已选择，不能重复选择");
		return;
	}
	var cateName = $("#item-cate-sele").val();
	var $option = $("#item-sele").find("option:selected");
	var itemName=$option.text();
	if(cateName=='套餐篇'){
		$.ajax({
			url : ctx+"/weixin/employee/shop/"+shopId+"/package/"+itemId+"/role",
			type : "GET",
			success : function(data) {
				$.each(data, function(i, item) {
					var price;
					if(vipId){
						price = item.vipPrice;
					}else{
						price = item.noVipPrice;
					}
					var $div = $(Comm.format(temp,itemId,item.serviceItemName+"("+itemName+")",1,price,item.noVipPrice));
					$div.find("input[name$='serviceItemId']").val(item.serviceItemId);
					$div.find("input[name$='packageId']").val(itemId);
					$div.appendTo(".am-g-striped");
					//解析数组
					$.each(item.roleRelaList, function(j, role) {
						var $html=$(Comm.format(empSelectTemp,j,role.roleId,role.roleName));
						$("<option/>").html("请选择").val("").appendTo($html.find('.item-emp-sele'));
						var emps = getEmpsByRoleId(role.roleId);
						if(emps){
							//解析数组
							$.each(emps, function(i, emp) {
								$("<option/>").html(emp.name+"("+emp.titleName+")").val(
										emp.employeeId).appendTo($html.find('.item-emp-sele'));
							});
						}
						$html.find('.item-emp-sele').selected({
							btnWidth: '100%',
							btnStyle: 'secondary'
						});
						$html.appendTo($div.find(".emp-sele-ul"));
					});

				});
				initNextServiceEmp();
				changeItemNum();
				$("#item-modal").modal('close');
			}
		});
	}else{
		var price=$option.data('price');
		var noVipPrice=$option.data('noVipPrice');
		var $div = $(Comm.format(temp,itemId,itemName,1,price,noVipPrice));
		$div.find("input[name$='serviceItemId']").val(itemId);
		$div.appendTo(".am-g-striped");

		$.ajax({
			url : ctx+"/weixin/employee/shop/"+shopId+"/service/"+itemId+"/role",
			type : "GET",
			success : function(data) {
				$.each(data, function(index, item) {
					var $html=$(Comm.format(empSelectTemp,index,item.roleId,item.roleName));
					$("<option/>").html("请选择").val("").appendTo($html.find('.item-emp-sele'));
					var emps = getEmpsByRoleId(item.roleId);
					if(emps){
						//解析数组
						$.each(emps, function(i, emp) {
							$("<option/>").html(emp.name+"("+emp.titleName+")").val(
									emp.employeeId).appendTo($html.find('.item-emp-sele'));
						});
					}
					$html.find('.item-emp-sele').selected({
						btnWidth: '100%',
						btnStyle: 'secondary'
					});
					$html.appendTo($div.find(".emp-sele-ul"));
				});

				initNextServiceEmp();
				changeItemNum();
				$("#item-modal").modal('close');
			}
		});
	}
});

$("#add-mdse-btn").click(function() {
	var mdseId = $("#mdse-sele").val();
	if(!mdseId){
		Comm.msg("请先选择商品");
		return;
	}
	var num = $("#mdse-num").html();
	var $mdseDiv = $("#"+mdseId);
	var $option = $("#mdse-sele").find("option:selected");
	var mdseName=$option.text();
	var price = $option.data("price");
	var noVipPrice = $option.data("no-vip-price");
	if($mdseDiv.length>0){
		$mdseDiv.data('num',num);
		mdseName=mdseName+" x"+num;
		$mdseDiv.find('.item-name').html(mdseName);
		$mdseDiv.find("input[name$='mdseNum']").val(num);
	}else{
		$mdseDiv = $(Comm.format(temp,mdseId,mdseName,num,price,noVipPrice));
		//$div.find(".emp-sele-ul").remove();
		$mdseDiv.attr('id',mdseId);
		$mdseDiv.find("input[name$='mdseId']").val(mdseId);
		mdseName=mdseName+" x"+num;
		$mdseDiv.find('.item-name').html(mdseName);
		$mdseDiv.appendTo(".am-g-striped");
		changeItemNum();
	}
	$("#good-modal").modal('close');
});

function checkServiceAndEmp(){
	var result = true;
	if($contentDiv.find('.am-text-blue').length==0){
		Comm.msg("请先选择服务项目和员工");
		return false;
	}
	if($contentDiv.find('.item-emp-sele').length>0){
		result = false;
		$contentDiv.find('.item-emp-sele').each(function(index) {
			if($(this).val()){
				result = true;
				return false;
			}
		});
	}
	if(!result){
		Comm.msg("请先选择服务项目和员工");
	}
	return result;
}

$("#next-btn").on("click",function(){
	if(!checkServiceAndEmp())
		return;
	var url = "/weixin/employee/orderSave";
	var orderScheduleId = $("#orderScheduleId").val();
	if(orderScheduleId){
		url = url+"?type=next";
	}
	orderSave(this,url);
});

$("#change-btn").on("click",function(){
	if(!checkServiceAndEmp())
		return;
	orderSave(this,"/weixin/employee/orderSave");
});

$("#pay-btn").on("click",function(){
	if(!checkServiceAndEmp())
		return;
	if(!confirm("是否确定结帐？")){
		return;
	}
	/*var flag = true;
	var orderScheduleId = $("#orderScheduleId").val();
	$contentDiv.find("input[name$='state']").each(function(index) {
		var state = $(this).val();
		if(state=='10A'){
			var $scheId = $(this).parent().prev().prev().prev();
			var name = $scheId.attr("name");
			if(name&&name.indexOf("orderScheduleId")>0){
				var tmpId = $scheId.val();
				if(tmpId!=orderScheduleId){
					flag = false;
					return false;
				}
			}else{
				flag = false;
				return false;
			}
		}
	});
	if(!flag){
		if(!confirm("还有未服务的项目，确定结帐？")){
			return;
		}
	}*/
	var orderInfoId = $("#orderInfoId").val();
	var url = "/weixin/employee/orderSave";
	if(orderScheduleId){
		url = url+"?type=next";
	}
	var $btn = $(this);
	var oldText = $btn.text();
	$btn.attr("disabled","disabled").text("正在提交...");
	$.ajax({
		type : 'POST',
		url: ctx+url,
		dataType: "json",
		data:$('form').serialize(),
		success: function (data) {
			$btn.prop("disabled",false).text(oldText);
			if (data.success) {
				window.location.href=ctx+"/weixin/employee/orderPay/"+orderInfoId;
			}else{
				Comm.msg("结算失败，请重试");
			}
		},
		error: function () {
			Comm.msg("结算失败，请重试");
			$btn.prop("disabled",false).text(oldText);
		}
	});
	//window.location.href=ctx+"/weixin/employee/orderPay/"+orderInfoId;
});

function orderSave(btn,url){
	var $nextEmp=$("#next-service-emp");
	if(!$nextEmp.val()){
		var flag = true;
		var orderScheduleId = $("#orderScheduleId").val();
		$contentDiv.find("input[name$='state']").each(function(index) {
			var state = $(this).val();
			if(state=='10A'){
				var $scheId = $(this).parent().prev().prev().prev();
				var name = $scheId.attr("name");
				if(name&&name.indexOf("orderScheduleId")>0){
					var tmpId = $scheId.val();
					if(tmpId!=orderScheduleId){
						flag = false;
						return false;
					}
				}else{
					flag = false;
					return false;
				}
			}
		});
		var orderInfoId = $("#orderInfoId").val();
		if(!flag){
			if(!confirm("还未选择下一步服务人员,是否确定提交?")){
				return;
			}
		}
	}
	var orderInfoId = $("#orderInfoId").val();
	var $btn = $(btn);
	var oldText = $btn.text();
	$btn.attr("disabled","disabled").text("正在提交...");
	$.ajax({
		type : 'POST',
		url: ctx+url,
		dataType: "json",
		data:$('form').serialize(),
		success: function (data) {
			$btn.prop("disabled",false).text(oldText);
			Comm.msg(data.msg);
			if (data.success) {
//				if(data.params&&data.params.pay){
//					window.location.href=ctx+"/weixin/employee/orderPay/"+orderInfoId;
//				}else{
//					setTimeout(function() {
//						window.location.href=ctx+"/weixin/employee/orderList";
//					}, 2000);
//				}
				setTimeout(function() {
					window.location.href=ctx+"/weixin/employee/orderList";
				}, 2000);
			}
		},
		error: function () {
			Comm.msg("提交失败，请重试");
			$btn.prop("disabled",false).text(oldText);
		}
	});
}
function initEmp(){
	employeeMap = null;
	//初始化下拉框
	$.ajax({
		url : ctx+"/weixin/employee/shop/"+shopId+"/employee",
		type : "GET",
		success : function(data) {
			employeeMap = data;
			initOrderScheEmp();
		}
	});
}

//已有订单时，加载员工列表
function initOrderScheEmp(){
	var orderInfoId = $("#orderInfoId").val();
	if(!orderInfoId){
		return;
	}
	$(".item-emp-sele").each(function(i) {
		var $select = $(this)
		var roleId = $select.prev().prev().val();
		var state = $select.prev().val();
		if(state=='10A'){
			var id = $select.val();
			var emps = getEmpsByRoleId(roleId);
			if(emps){
				$select.empty();
				$("<option/>").html("请选择").val("").appendTo($select);
				$.each(emps, function(i, emp) {
					if(emp.employeeId == id){
						$("<option/>").html(emp.name+"("+emp.titleName+")").val(
								emp.employeeId).attr('selected',true).appendTo($select);
					}else{
						$("<option/>").html(emp.name+"("+emp.titleName+")").val(
								emp.employeeId).appendTo($select);
					}
				});
				if (!$.AMUI.support.mutationobserver) {
					$select.trigger('changed.selected.amui');
				}
			}
		}
	});
}

function getEmpsByRoleId(roleId){
	var emps = employeeMap[roleId];
	if(!emps){
		emps = [];
	}
	if(roleId=="XFS"){
		var fxsEmps = employeeMap["FXS"];
		if(fxsEmps)
			emps = emps.concat(fxsEmps);
		var rtsEmps = employeeMap["RTS"];
		if(rtsEmps)
			emps = emps.concat(rtsEmps);
	}else if(roleId=="RTS"){
		var fxsEmps = employeeMap["FXS"];
		if(fxsEmps)
			emps = emps.concat(fxsEmps);
	}
	return emps;
}

//function detail(){
//	window.location.href=ctx+"/weixin/employee/vipDetail/"+vipId;
//}

function vipDetail(){
	$('#vip-detail').offCanvas("open");
	//$('#vip-detail iframe').attr("src","weixin/employee/vipDetail/"+vipId+"?isIframe");
}

function serviceRecord(){
	$('#service-record-detail').offCanvas("open");
	//$('#service-record-detail iframe').attr("src","weixin/employee/serviceRecord/"+vipId);
}

$(".close-offcanvas-btn").on("click",function(){
	var $oc = $(this).parents(".am-offcanvas");
	$oc.offCanvas("close");
});
//项目初始化
initEmp();
initItemModal();
chanageMdsePrice($("#mdse-sele").find("option:selected").data("price"));
changeItemNum();
//修改浏览器历史的url地址
var orderInfoId = $("#orderInfoId").val();
if(orderInfoId){
	var href = window.location.href;
	if(href.indexOf('#forward')<0)
		window.history.replaceState('forward', null, href+'#forward');
	else
		window.location.href=href.substring(0,href.indexOf('#forward'));
}